package com.zisuyi.uilibrary.view

import android.animation.ValueAnimator
import android.content.Context
import android.util.AttributeSet
import com.weilele.mvvm.base.helper.ILifecycleObserver
import com.weilele.mvvm.utils.activity.getActivity
import com.zisuyi.uilibrary.base.BaseUiViewModel

class CoinTextView : FontTextView, ILifecycleObserver {
    private var isResume = false
    private var numAnim: ValueAnimator? = null

    constructor(context: Context) : this(context, null)
    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    ) {
        getActivity()?.lifecycle?.addObserver(this)
    }

    private val listener = ValueAnimator.AnimatorUpdateListener { p0 ->
        val currentNum = p0.animatedValue as Int
        text = currentNum.toString()
    }

    fun setNumber(num: Long?) {
        num ?: return
        val oldNum = text.toString().replace(",", "").toInt()
        val newNum = num.toInt()
        if (oldNum == newNum) {
            return
        }
        if (isResume) {
            numAnim?.cancel()
            numAnim = ValueAnimator.ofInt(oldNum, newNum)
            numAnim?.duration = 400
            numAnim?.addUpdateListener(listener)
            numAnim?.start()
        } else {
            text = num.toString()
        }
    }

    override fun onResume() {
        isResume = true
    }

    override fun onPause() {
        isResume = false
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        BaseUiViewModel.coinViews.remove(this)
        numAnim?.cancel()
    }

    override fun onAttachedToWindow() {
        super.onAttachedToWindow()
        BaseUiViewModel.coinViews.add(this)
    }
}